package com.gp.shaw.netty.io.im;

import com.gp.shaw.netty.io.im.model.IMMsg;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by asus on 2018/11/1.
 */
public class IMServer {
    private final static int DEFAULT_PROT=8080;

    private int port= DEFAULT_PROT;

    private ServerSocket serverSocket = null;

    //接收消息的线程池
    private ExecutorService executorService = null;

    //用户管理者
    private static UserManager userManager = new UserManager();;

    //消息队列
    private static LinkedBlockingQueue<IMMsg> msgQueue = new LinkedBlockingQueue<>();

    //消息发送线程
    private SendThread sendThread = null;

    public IMServer(int port){
        this.port = port;
    }
    public void start(){
        startPre();
        try {
            System.out.println("IM服务启动，端口号："+port);
            serverSocket = new ServerSocket(port);
            //开启发送轮询线程
            sendThread.start();
            //消息接收线程
            while(true){
                Socket socket = serverSocket.accept();
                executorService.execute(new IMHandler(socket,userManager,msgQueue));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close();
        }
    }

    public void startPre(){
        if(serverSocket!=null){
            return;
        }
        if(executorService==null){
            executorService = Executors.newFixedThreadPool(100);
        }
        if(sendThread == null){
            sendThread = new SendThread(msgQueue,userManager);
        }
    }

    public void close(){
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        serverSocket = null;

        executorService.shutdown();
        executorService = null;
        sendThread.interrupt();
        sendThread = null;
    }

    public static void main(String[] args) {
        IMServer server = new IMServer(8080);
        server.start();
    }
}
